package com.redwine.app;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.redwine.app.net.GsonRequest;
import com.redwine.app.net.NetworkConstants;
import com.redwine.app.net.model.User;
import com.redwine.app.net.responses.BaseResponse;
import com.redwine.app.net.responses.DownOptionsBean;
import com.redwine.app.net.responses.UserResponse;
import com.redwine.app.utils.Global;
import com.redwine.app.utils.NetUtil;
import com.redwine.app.utils.Settings;

import java.util.LinkedHashMap;
import java.util.Map;

import static com.redwine.app.utils.Utils.showToast;

/**
 * 个人的基本信息页面
 * 作者：gassion on 17/8/31 23:26
 * 最可怕的敌人，就是没有坚强的信念。
 */
public class PersonalBasicInformationActivity extends BaseActivity {

    @ViewInject(R.id.header_title)
    private TextView headerTitle;
    @ViewInject(R.id.layout_back)
    private LinearLayout layoutBack;
    @ViewInject(R.id.basic_info_et_nickname)
    private EditText basicInfoEtNickname;
    @ViewInject(R.id.basic_info_et_merchants_nickname)
    private EditText basicInfoEtMerchantsNickname;
    @ViewInject(R.id.basic_info_tv_phone)
    private TextView basicInfoTPhone;
    @ViewInject(R.id.basic_info_tv_countries)
    private TextView basicInfoTvCountries;
    @ViewInject(R.id.basic_info_tv_home)
    private TextView basicInfoTvHome;
    @ViewInject(R.id.basic_info_et_address)
    private EditText basicInfoEtAddress;
    private Intent intent;
    private static final int COUNTRIES_REQUEST_CODE = 11;
    private static final int HOME_REQUEST_CODE = 12;
    public static final int RESULT_CODE = 200;
    private DownOptionsBean mCountriesBean;
    private DownOptionsBean mHomeBean;
    private UserResponse.DataEntity responseData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personal_basic_info);
        ViewUtils.inject(this);
        initView();
        requestGetMyData();
    }

    private void initView() {
        headerTitle.setText(R.string.personal_center_basic_information);
        layoutBack.setVisibility(View.VISIBLE);
    }

    @OnClick({R.id.layout_back, R.id.basic_info_tv_save, R.id.basic_info_ll_countries, R.id.basic_info_ll_home})
    public void mClick(View v) {
        switch (v.getId()) {

            case R.id.layout_back:
                finish();
                break;

            case R.id.basic_info_tv_save:
                submit();
                break;

            case R.id.basic_info_ll_home:
                //所在地
                intent = new Intent(getApplication(), PersonalInfoAddressActivity.class);
                intent.putExtra(PersonalInfoAddressActivity.COUNTRIES_FLAG, false);
                startActivityForResult(intent, HOME_REQUEST_CODE);
                break;

            case R.id.basic_info_ll_countries:
                //国家
                intent = new Intent(getApplication(), PersonalInfoAddressActivity.class);
                intent.putExtra(PersonalInfoAddressActivity.COUNTRIES_FLAG, true);
                startActivityForResult(intent, COUNTRIES_REQUEST_CODE);
                break;

        }
    }


    /**
     * 提交信息
     */
    private void submit() {
        final String nickname = basicInfoEtNickname.getText().toString().trim();
        if (TextUtils.isEmpty(nickname)) {
            Toast.makeText(this, "昵称不能为空!", Toast.LENGTH_SHORT).show();
            return;
        }

        String merchantsNickname = basicInfoEtMerchantsNickname.getText().toString().trim();
        if (TextUtils.isEmpty(merchantsNickname)) {
            Toast.makeText(this, "商家昵称不能为空!", Toast.LENGTH_SHORT).show();
            return;
        }

        String countries = basicInfoTvCountries.getText().toString().trim();
        if (TextUtils.isEmpty(countries)) {
            Toast.makeText(this, "国家不能为空!", Toast.LENGTH_SHORT).show();
            return;
        }

        String home = basicInfoTvHome.getText().toString().trim();
        if (TextUtils.isEmpty(home)) {
            Toast.makeText(this, "所在地不能为空!", Toast.LENGTH_SHORT).show();
            return;
        }

        String address = basicInfoEtAddress.getText().toString().trim();
        if (TextUtils.isEmpty(address)) {
            Toast.makeText(this, "详细地址不能为空!", Toast.LENGTH_SHORT).show();
            return;
        }

        showWaiting();
        String url = NetworkConstants.MY_DATA_SET_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("uid", Global.user.getUid());
        params.put("name", merchantsNickname);
        params.put("nickname", nickname);
        if (null != mCountriesBean)
            params.put("country", mCountriesBean.getId());
        else
            params.put("country", responseData.getCountry_id());
        if (null != mHomeBean)
            params.put("city", mHomeBean.getId());
        else
            params.put("city", responseData.getCity_id());
        params.put("address", address);
        GsonRequest<BaseResponse> request = new GsonRequest<>(url, Request.Method.POST,
                BaseResponse.class, false, params, new Response.Listener<BaseResponse>() {
            @Override
            public void onResponse(BaseResponse response) {
                dismissWaiting();
                if (null != Global.user) {
                    Gson gson = new Gson();
                    User user = Global.user;
                    user.setNickname(nickname);
                    String json = gson.toJson(user);
                    Settings.saveProfile(json);//
                    Global.setUser(json); //保存登录信息
                }
                showToast(response.getMsg());
                finish();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                dismissWaiting();
            }
        });
        APP.getInstance().getRequestQueue().add(request);
    }


    /**
     * 获取个人信息
     */
    private void requestGetMyData() {
        if (!NetUtil.checkNet(this)) {
            showToast(R.string.generic_check);
            return;
        }

        showWaiting();
        String url = NetworkConstants.MY_DATA_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("uid", Global.user.getUid());
        GsonRequest<UserResponse> request = new GsonRequest<>(url, Request.Method.POST,
                UserResponse.class, false, params, new Response.Listener<UserResponse>() {
            @Override
            public void onResponse(UserResponse response) {
                dismissWaiting();
                if (response.isSuccess()) {
                    responseData = response.getData();
                    updateView(responseData);
                } else {
                    showToast(response.getMsg());
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                dismissWaiting();
                showToast(error.getMessage());
            }
        });
        APP.getInstance().getRequestQueue().add(request);
    }

    /**
     * 更新显示view
     *
     * @param dataEntity
     */
    private void updateView(UserResponse.DataEntity dataEntity) {
        if (!TextUtils.isEmpty(dataEntity.getName())) {
            basicInfoEtMerchantsNickname.setText(dataEntity.getName());
            basicInfoEtMerchantsNickname.setSelection(dataEntity.getName().length());
        }
        if (!TextUtils.isEmpty(dataEntity.getMobile())) {
            basicInfoTPhone.setText(dataEntity.getMobile());
        }
        if (!TextUtils.isEmpty(dataEntity.getCountry())) {
            basicInfoTvCountries.setText(dataEntity.getCountry());
        }
        if (!TextUtils.isEmpty(dataEntity.getCity())) {
            basicInfoTvHome.setText(dataEntity.getCity());
        }
        if (!TextUtils.isEmpty(dataEntity.getAddress())) {
            basicInfoEtAddress.setText(dataEntity.getAddress());
            basicInfoEtAddress.setSelection(dataEntity.getAddress().length());
        }
        if (!TextUtils.isEmpty(dataEntity.getNickname())) {
            basicInfoEtNickname.setText(dataEntity.getNickname());
            basicInfoEtNickname.setSelection(dataEntity.getNickname().length());
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == HOME_REQUEST_CODE && resultCode == RESULT_CODE) {
            mHomeBean = (DownOptionsBean) data.getSerializableExtra(PersonalInfoAddressActivity.SET_DATA);
            basicInfoTvHome.setText(mHomeBean.getName());
        } else if (requestCode == COUNTRIES_REQUEST_CODE && resultCode == RESULT_CODE) {
            mCountriesBean = (DownOptionsBean) data.getSerializableExtra(PersonalInfoAddressActivity.SET_DATA);
            basicInfoTvCountries.setText(mCountriesBean.getName());
        }
    }
}
